package com.greenhouse9.prog07;

import java.io.*;


/**
 * Sequence.java
 *
 * (C) music-of-chance
 */
public class Sequence
{

    private int sequence;

    Sequence (String filename) {

        File file = new File(filename);

        if (file.isFile()) {
            try {
                InputStream in = new FileInputStream(file);
                int ch;
                byte [] b = new byte [128];
                short start = 0;
                short end   = 0;
                short flag = 0;
                while ((ch = in.read(b)) != -1){

                    for(short i=0; i<b.length; i++){
                        if( b[i] >= 0x30 && b[i] <=0x39 ){
                            if( flag == 0 ){
                                start = i;
                                flag  = 1;
                            }
                            end = i;
                        }
                    }
                }
                in.close();

                String s = new String(b, start, end-start+1);
                //System.out.println(s); // for debug
                sequence = Integer.parseInt(s);
            }
            catch (IOException e) {
                e.printStackTrace();
            }

            String up = String.valueOf(sequence + 1);
            try {
                FileWriter fw = new FileWriter (file);

                fw.write(up, 0, up.length());
                fw.flush();
                fw.close();

            }
            catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public int getSequence(){
        return sequence;
    }

}
